'''
Created on Sep 8, 2011

@author: sevear
'''
import urllib2,json,web

class DBUserAPI(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    _searchUid = None

    def searchDBUser(self,uid):
        if(isinstance(uid,(int,long,float))):
            uid = str(uid)
        self._searchUid = uid
        url = 'http://api.douban.com/people?q=%s&start-index=%d&max-results=%d&alt=json'%(uid,0,10)
        req=urllib2.Request(url)
        res = urllib2.urlopen(req) 
        jsonstr = res.read() 
        res.close() 
        result = self.parseResult(json.loads(jsonstr))
        if(result!=None):
            user = dict();
            user["dbuid"] = result["db:uid"]["$t"]
            user["dburl"] = result["uri"]["$t"]
            id =  str(result["uri"]["$t"])[len("http://api.douban.com/people/"):]
            id = int(id)
            user["uid"] = id
            user["name"] = result["title"]["$t"]
            user["headimg"] = result["link"][2]["@href"]
            user["tolist"] = None
            user["sendlist"] = None
            user["enable"] = 0
            user["version"] = None
            user["activietime"] = None
            user["isactivate"] = 0
            return web.utils.storify(user)
        else:
            return None
    
    def parseResult(self,result):
        print result["openSearch:totalResults"]["$t"];
        for user in result["entry"]:
            if(user["db:uid"]["$t"]==self._searchUid):
                return user;
            else:
                id =  str(user["uri"]["$t"])[len("http://api.douban.com/people/"):]
                if(id == self._searchUid):
                    return user
        return None;
    
if __name__ == '__main__':
    api = DBUserAPI()
#    resultUser = api.searchDBUser("sevear")
    result = api.searchDBUser("sevear");
    if(result!=None):
        user = dict();
        user["dbuid"] = result["db:uid"]["$t"]
        user["dburl"] = result["uri"]["$t"]
        id =  str(result["uri"]["$t"])[len("http://api.douban.com/people/"):]
        id = int(id)
        user["uid"] = id
        user["name"] = result["title"]["$t"]
        user["headimg"] = result["link"][2]["@href"]
        user["tolist"] = None
        user["sendlist"] = None
        user["enable"] = 0
        user["version"] = None
        user["activietime"] = None
        user["isactivate"] = 0
    print user;